<?php

namespace app\portal\controller;

use addons\wechat\model\WechatCaptcha;
use app\common\controller\Frontend;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\Attachment;
use think\Config;
use think\Cookie;
use think\Hook;
use think\Session;
use think\Validate;
use fast\Tree;

/**
 * 会员中心
 */
class Alipay extends Frontend
{
    protected $layout = 'default';
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $model = null;

    public function _initialize()
    { 
        parent::_initialize();
        $auth = $this->auth;

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

        //监听注册登录退出的事件
        Hook::add('user_login_successed', function ($user) use ($auth) {
            $expire = input('post.keeplogin') ? 30 * 86400 : 0;
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);
        });
        Hook::add('user_register_successed', function ($user) use ($auth) {
            Cookie::set('uid', $user->id);
            Cookie::set('token', $auth->getToken());
        });
        Hook::add('user_delete_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
        Hook::add('user_logout_successed', function ($user) use ($auth) {
            Cookie::delete('uid');
            Cookie::delete('token');
        });
        $this->model = new \app\admin\model\yexam\Subject;
    }
    /**
     * 注册会员
     */
    public function zhukao()
    {
        $url = $this->request->request('url', '', 'trim');
        $source = $this->request->request('source', '', 'trim');
        $ename = $this->request->request('ename', '', 'trim');
        $cn_name = '';
        if($ename){
            $row = $this->model->get(['en_name'=>$ename]);
            if($row) $cn_name = $row['short_name'];
        }
        $client = cmf_is_mobile() ? 'm' : 'pc';
        if ($this->auth->id) {
            $gourl = cmf_is_mobile() ? 'http://h5.zhukao.com.cn/index.php' : 'http://h5.zhukao.com.cn/index1.php';

            $agentId = '1146';
            $ageniUId = $this->auth->id;
            $safeKey = 'C864J3ZUZBZK1146';
            $aqkey = md5($agentId.$ageniUId.$safeKey);
            if(!empty($ename)){
                $keMu = $ename;
                $zhukaourl = $gourl.'?g=agentUrl&agentId='.$agentId.'&agentUId='.$ageniUId.'&keMu='.$keMu.'&f=Browser&aqKey='.$aqkey;
                //header('location:' .$zhukaourl);
                //exit;
            }else{
                $zhukaourl = $gourl.'?g=agentUrl&agentId='.$agentId.'&agentUId='.$ageniUId.'&f=Browser&aqKey='.$aqkey;
                //header('location:'. $zhukaourl);
                //exit;
            }
            //header('location:'.url('index/common/zkhead',array('zkurl'=>urlencode(urlencode($zhukaourl)))));exit;
            header('location:'.$zhukaourl);exit;
        }
        if ($this->request->isPost()) {
            // $username = $this->request->post('username');
            $password = $this->request->post('password');
            // $email = $this->request->post('email');
            $email = '';
            $mobile = $this->request->post('mobile', '');
            $captcha = $this->request->post('captcha');
            $token = $this->request->post('__token__');
            $rule = [
                // 'username'  => 'require|length:3,30',
                'password'  => 'require|length:6,30',
                // 'email'     => 'require|email',
                'mobile'    => 'regex:/^1\d{10}$/',
                '__token__' => 'require|token',
            ];

            $msg = [
                // 'username.require' => 'Username can not be empty',
                // 'username.length'  => 'Username must be 3 to 30 characters',
                'password.require' => '密码不能为空',
                'password.length'  => '密码长度须为6-30个字符',
                // 'email'            => 'Email is incorrect',
                'mobile'           => '手机号输入有误！',
            ];
            $data = [
                // 'username'  => $username,
                'password'  => $password,
                // 'email'     => $email,
                'mobile'    => $mobile,
                '__token__' => $token,
            ];
            //验证码
            $captchaResult = true;
            $captchaType = config("fastadmin.user_register_captcha");
            if ($captchaType) {
                if ($captchaType == 'mobile') {
                    $captchaResult = Sms::check($mobile, $captcha, 'register');
//                } elseif ($captchaType == 'email') {
//                    $captchaResult = Ems::check($email, $captcha, 'register');
                } elseif ($captchaType == 'wechat') {
                    $captchaResult = WechatCaptcha::check($captcha, 'register');
                } elseif ($captchaType == 'text') {
                    $captchaResult = \think\Validate::is($captcha, 'captcha');
                }
            }
            if (!$captchaResult) {
                $this->error(__('Captcha is incorrect'));
            }
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
            }
            $username = $mobile;
            if($this->auth->isUser($mobile)){
                if ($this->auth->login($mobile, $password)) {

                } else {
                    $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
                }
            }else{
                // Set default username, email...

                $extend['entry_platform'] = $client;
                $extend['url_source'] = $source;
                $extend['class_name'] = $ename;
                $extend['class_title'] = $cn_name;
                if ($this->auth->register($username, $password, $email, $mobile,$extend)) {

                } else {
                    $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
                }
            }

            // 考试宝典处理
            $website = cmf_get_website_value();
            $ksbao_data = [
                'userName' => $username,
                'password' => $password,
                'client'   => $client,
                'partnercode' => $website['partnercode'],
            ];
            $ksbao_reg_url = cmf_get_ksbao_value('nregist');
            $json = cmf_send_post($ksbao_reg_url, $ksbao_data, $website['client_ip']);
            $return_arr = json_decode($json, true);
            if ($return_arr['status'] = 200) \session('guid', $return_arr['data']['guid']);

            $gourl = cmf_is_mobile() ? 'http://h5.zhukao.com.cn/index.php' : 'http://h5.zhukao.com.cn/index1.php';
            $agentId = '1146';
            $ageniUId = $this->auth->id;
            $safeKey = 'C864J3ZUZBZK1146';
            $aqkey = md5($agentId.$ageniUId.$safeKey);
            if(!empty($ename)){
                $keMu = $ename;
                $zhukaourl = $gourl.'?g=agentUrl&agentId='.$agentId.'&agentUId='.$ageniUId.'&keMu='.$keMu.'&f=Browser&aqKey='.$aqkey;
                //header('location:' .$zhukaourl);
                //exit;
            }else{
                $zhukaourl = $gourl.'?g=agentUrl&agentId='.$agentId.'&agentUId='.$ageniUId.'&f=Browser&aqKey='.$aqkey;
            }
            //echo("<script language='javascript'>window.top.location.href='".$zhukaourl."'</script>");exit;
            $this->success('登录成功',$zhukaourl);
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register|user\/logout)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('captchaType', config('fastadmin.user_register_captcha'));
        $this->view->assign('url', $url);
        $this->view->assign('ename', $ename);
        $this->view->assign('cn_name', $cn_name);
        $this->view->assign('source', $source);
        $this->view->assign('title', __('Register'));
        return $this->view->fetch();
    }

    /**
     * 注册会员
     */
    public function index()
    {
        $url = $this->request->request('url', '', 'trim');
        $source = $this->request->request('source', '', 'trim');
        $ename = $this->request->request('ename', '', 'trim');
        $cn_name = '';
        if($ename){
            $row = $this->model->get(['en_name'=>$ename]);
            if($row) $cn_name = $row['short_name'];
        }
        $client = cmf_is_mobile() ? 'm' : 'pc';
        if ($this->auth->id) {
//            $this->success(__('You\'ve logged in, do not login again'), $url ? $url : url('index/index'));
            $ename = $ename ? : $this->auth->class_name;
            header('location:'. url('index/Common/head',array('enname'=>$ename,'client'=>$client)));
            exit;
        }
        if ($this->request->isPost()) {
            // $username = $this->request->post('username');
            $password = $this->request->post('password');
            // $email = $this->request->post('email');
            $email = '';
            $mobile = $this->request->post('mobile', '');
            $captcha = $this->request->post('captcha');
            $token = $this->request->post('__token__');
            $rule = [
                // 'username'  => 'require|length:3,30',
                'password'  => 'require|length:6,30',
                // 'email'     => 'require|email',
                'mobile'    => 'regex:/^1\d{10}$/',
                '__token__' => 'require|token',
            ];

            $msg = [
                // 'username.require' => 'Username can not be empty',
                // 'username.length'  => 'Username must be 3 to 30 characters',
                'password.require' => '密码不能为空',
                'password.length'  => '密码长度须为6-30个字符',
                // 'email'            => 'Email is incorrect',
                'mobile'           => '手机号输入有误！',
            ];
            $data = [
                // 'username'  => $username,
                'password'  => $password,
                // 'email'     => $email,
                'mobile'    => $mobile,
                '__token__' => $token,
            ];
            //验证码
            $captchaResult = true;
            $captchaType = config("fastadmin.user_register_captcha");
            if ($captchaType) {
                if ($captchaType == 'mobile') {
                    $captchaResult = Sms::check($mobile, $captcha, 'register');
//                } elseif ($captchaType == 'email') {
//                    $captchaResult = Ems::check($email, $captcha, 'register');
                } elseif ($captchaType == 'wechat') {
                    $captchaResult = WechatCaptcha::check($captcha, 'register');
                } elseif ($captchaType == 'text') {
                    $captchaResult = \think\Validate::is($captcha, 'captcha');
                }
            }
            if (!$captchaResult) {
                $this->error(__('Captcha is incorrect'));
            }
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
            }
            $username = $mobile;
            if($this->auth->isUser($mobile)){
                if ($this->auth->login($mobile, $password)) {

                } else {
                    $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
                }
            }else{
                // Set default username, email...

                $extend['entry_platform'] = $client;
                $extend['url_source'] = $source;
                $extend['class_name'] = $ename;
                $extend['class_title'] = $cn_name;
                if ($this->auth->register($username, $password, $email, $mobile,$extend)) {

                } else {
                    $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
                }
            }

            // ksbao 同步注册
            $website = cmf_get_website_value();
            $ksbao_data = [
                'userName' => $username,
                'password' => $password,
                'client'   => $client,
                'partnercode' => $website['partnercode'],
            ];
            $ksbao_reg_url = cmf_get_ksbao_value('nregist');
            $json = cmf_send_post($ksbao_reg_url, $ksbao_data, $website['client_ip']);
            $return_arr = json_decode($json, true);
            if ($return_arr['status'] != 200) {
                $this->error('同步失败,请联系管理员');
            } else {
                $appEName =  $ename ? :($return_arr['data']['appEName'] ?? '');
//                $appVn =  $data['vn'] ?? ($return_arr['data']['appVn'] ?? 0);
                \session('guid', $return_arr['data']['guid']);
            }
            // /ksbao 同步注册

//                $this->success(__('Sign up successful'), $url ? $url : url('user/index'));
//            var_dump(url('Common/head',array('enname'=>$appEName,'client'=>$client)));exit;
            $this->success('注册/登录成功', url('index/Common/head',array('enname'=>$appEName,'client'=>$client)));
        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register|user\/logout)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('captchaType', config('fastadmin.user_register_captcha'));
        $this->view->assign('url', $url);
        $this->view->assign('ename', $ename);
        $this->view->assign('cn_name', $cn_name);
        $this->view->assign('source', $source);
        $this->view->assign('title', __('牛课宝典首页'));
        return $this->view->fetch();
    }
	
	public function mindex(){
		$url = $this->request->request('url', '', 'trim');
        $source = $this->request->request('source', '', 'trim');
        $ename = $this->request->request('ename', '', 'trim');
        $cn_name = '';
        if($ename){
            $row = $this->model->get(['en_name'=>$ename]);
            if($row) $cn_name = $row['short_name'];
        }
        $client = cmf_is_mobile() ? 'm' : 'pc';
        if ($this->auth->id) {
            header('location:'. url('index/user/index'));
            exit;
        }
        if ($this->request->isPost()) {
            // $username = $this->request->post('username');
            $password = $this->request->post('password');
            // $email = $this->request->post('email');
            $email = '';
            $mobile = $this->request->post('mobile', '');
            $captcha = $this->request->post('captcha');
            $token = $this->request->post('__token__');
            $rule = [
                // 'username'  => 'require|length:3,30',
                'password'  => 'require|length:6,30',
                // 'email'     => 'require|email',
                'mobile'    => 'regex:/^1\d{10}$/',
                '__token__' => 'require|token',
            ];

            $msg = [
                // 'username.require' => 'Username can not be empty',
                // 'username.length'  => 'Username must be 3 to 30 characters',
                'password.require' => '密码不能为空',
                'password.length'  => '密码长度须为6-30个字符',
                // 'email'            => 'Email is incorrect',
                'mobile'           => '手机号输入有误！',
            ];
            $data = [
                // 'username'  => $username,
                'password'  => $password,
                // 'email'     => $email,
                'mobile'    => $mobile,
                '__token__' => $token,
            ];
            //验证码
            $captchaResult = true;
            $captchaType = config("fastadmin.user_register_captcha");
            if ($captchaType) {
                if ($captchaType == 'mobile') {
                    $captchaResult = Sms::check($mobile, $captcha, 'register');
//                } elseif ($captchaType == 'email') {
//                    $captchaResult = Ems::check($email, $captcha, 'register');
                } elseif ($captchaType == 'wechat') {
                    $captchaResult = WechatCaptcha::check($captcha, 'register');
                } elseif ($captchaType == 'text') {
                    $captchaResult = \think\Validate::is($captcha, 'captcha');
                }
            }
            if (!$captchaResult) {
                $this->error(__('Captcha is incorrect'));
            }
            $validate = new Validate($rule, $msg);
            $result = $validate->check($data);
            if (!$result) {
                $this->error(__($validate->getError()), null, ['token' => $this->request->token()]);
            }
            $username = $mobile;
            if($this->auth->isUser($mobile)){
                if ($this->auth->login($mobile, $password)) {

                } else {
                    $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
                }
            }else{
                // Set default username, email...

                $extend['entry_platform'] = $client;
                $extend['url_source'] = $source;
                $extend['class_name'] = $ename;
                $extend['class_title'] = $cn_name;
                if ($this->auth->register($username, $password, $email, $mobile,$extend)) {

                } else {
                    $this->error($this->auth->getError(), null, ['token' => $this->request->token()]);
                }
            }
			// ksbao 同步注册
            $website = cmf_get_website_value();
            $ksbao_data = [
                'userName' => $username,
                'password' => $password,
                'client'   => $client,
                'partnercode' => $website['partnercode'],
            ];
            $ksbao_reg_url = cmf_get_ksbao_value('nregist');
            $json = cmf_send_post($ksbao_reg_url, $ksbao_data, $website['client_ip']);
            $return_arr = json_decode($json, true);
            if ($return_arr['status'] != 200) {
                $this->error('同步失败,请联系管理员');
            } else {
                $appEName =  $ename ? :($return_arr['data']['appEName'] ?? '');
//                $appVn =  $data['vn'] ?? ($return_arr['data']['appVn'] ?? 0);
                \session('guid', $return_arr['data']['guid']);
            }
			$this->success('注册/登录成功', url('index/user/index'));

        }
        //判断来源
        $referer = $this->request->server('HTTP_REFERER');
        if (!$url && (strtolower(parse_url($referer, PHP_URL_HOST)) == strtolower($this->request->host()))
            && !preg_match("/(user\/login|user\/register|user\/logout)/i", $referer)) {
            $url = $referer;
        }
        $this->view->assign('captchaType', config('fastadmin.user_register_captcha'));
        $this->view->assign('url', $url);
        $this->view->assign('ename', $ename);
        $this->view->assign('cn_name', $cn_name);
        $this->view->assign('source', $source);
        $this->view->assign('title', __('Register'));
        return $this->view->fetch();
	}

	public function yishi(){
        $cid = $this->request->param('cid');
        $category_id = 15;
        $res = $this->cate_load($category_id,$cid);
        $categorydata = $res['categorydata'];
        $category = $res['category'];
        $this->view->assign('categorydata', $categorydata);
        $this->view->assign('category', $category);
		$this->view->assign('title',date('Y'). __('年执业医师资格考试'));
        return $this->view->fetch('common');
		}
	public function yaoshi(){
        $cid = $this->request->param('cid');
        $category_id = 16;
        $res = $this->cate_load($category_id,$cid);
        $categorydata = $res['categorydata'];
        $category = $res['category'];
        $this->view->assign('categorydata', $categorydata);
        $this->view->assign('category', $category);
		$this->view->assign('title',date('Y'). __('年执业药师考试'));
        return $this->view->fetch('common');
		}
	public function wszg(){
        $cid = $this->request->param('cid');
        $category_id = 19;
        $res = $this->cate_load($category_id,$cid);
        $categorydata = $res['categorydata'];
        $category = $res['category'];
        $this->view->assign('categorydata', $categorydata);
        $this->view->assign('category', $category);
		$this->view->assign('title',date('Y'). __('年卫生中级职称考试'));
        return $this->view->fetch('common');
		}
	public function wscj(){
        $cid = $this->request->param('cid');
        $category_id = 20;
        $res = $this->cate_load($category_id,$cid);
        $categorydata = $res['categorydata'];
        $category = $res['category'];
        $this->view->assign('categorydata', $categorydata);
        $this->view->assign('category', $category);
		$this->view->assign('title',date('Y'). __('年卫生中级职称考试'));
        return $this->view->fetch('common');
		}
	public function fugao(){
        $cid = $this->request->param('cid');
        $category_id = 17;
        $res = $this->cate_load($category_id,$cid);
        $categorydata = $res['categorydata'];
        $category = $res['category'];
        $this->view->assign('categorydata', $categorydata);
        $this->view->assign('category', $category);
		$this->view->assign('title',date('Y'). __('年卫生副高职称考试'));
        return $this->view->fetch('common');
		}
	public function gaoji(){
        $cid = $this->request->param('cid');
        $category_id = 18;

        $res = $this->cate_load($category_id,$cid);
        $categorydata = $res['categorydata'];
        $category = $res['category'];
        
        $this->view->assign('categorydata', $categorydata);
        $this->view->assign('category', $category);
		$this->view->assign('title',date('Y'). __('年卫生正高职称考试'));
        return $this->view->fetch('common');
		}
	public function hushi(){
        $cid = $this->request->param('cid');
        $category_id = 21;
		
        $res = $this->cate_load($category_id,$cid);
        $categorydata = $res['categorydata'];
        $category = $res['category'];
        
        $this->view->assign('categorydata', $categorydata);
        $this->view->assign('category', $category);
		$this->view->assign('title',date('Y'). __('年护士执业资格考试'));
        return $this->view->fetch('common');
		}
	public function yaoxue(){
        $cid = $this->request->param('cid');
        $category_id = 31;

        $res = $this->cate_load($category_id,$cid);
        $categorydata = $res['categorydata'];
        $category = $res['category'];
        
        $this->view->assign('categorydata', $categorydata);
        $this->view->assign('category', $category);
		$this->view->assign('title',date('Y'). __('年药学职称考试'));
        return $this->view->fetch('common');
		}
	public function zhaopin(){
        $cid = $this->request->param('cid');
        $category_id = 24;

        $res = $this->cate_load($category_id,$cid);
        $categorydata = $res['categorydata'];
        $category = $res['category'];
        
        $this->view->assign('categorydata', $categorydata);
        $this->view->assign('category', $category);
		$this->view->assign('title',date('Y'). __('年医学招聘考试'));
        return $this->view->fetch('common');
		}
	public function zhuyuan(){
        $cid = $this->request->param('cid');
        $category_id = 24;

        $res = $this->cate_load($category_id,$cid);
        $categorydata = $res['categorydata'];
        $category = $res['category'];
        
        $this->view->assign('categorydata', $categorydata);
        $this->view->assign('category', $category);
		$this->view->assign('title',date('Y'). __('年住院医师规范化培训考试'));
        return $this->view->fetch('common');
		}
	public function shebei(){
        $cid = $this->request->param('cid');
        $category_id = 24;

        $res = $this->cate_load($category_id,$cid);
        $categorydata = $res['categorydata'];
        $category = $res['category'];
        
        $this->view->assign('categorydata', $categorydata);
        $this->view->assign('category', $category);
		$this->view->assign('title',date('Y'). __('年大型设备上岗考试'));
        return $this->view->fetch('common');
		}
	public function jingji(){
        $cid = $this->request->param('cid');
        $category_id = 24;

        $res = $this->cate_load($category_id,$cid);
        $categorydata = $res['categorydata'];
        $category = $res['category'];
        
        $this->view->assign('categorydata', $categorydata);
        $this->view->assign('category', $category);
		$this->view->assign('title',date('Y'). __('年经济师初中高级考试'));
        return $this->view->fetch('common');
		}
	public function jianzhu(){
        $cid = $this->request->param('cid');
        $category_id = 24;

        $res = $this->cate_load($category_id,$cid);
        $categorydata = $res['categorydata'];
        $category = $res['category'];
        
        $this->view->assign('categorydata', $categorydata);
        $this->view->assign('category', $category);
		$this->view->assign('title',date('Y'). __('年建筑工程考试'));
        return $this->view->fetch('common');
		}
	public function caikuai(){
        $cid = $this->request->param('cid');
        $category_id = 24;

        $res = $this->cate_load($category_id,$cid);
        $categorydata = $res['categorydata'];
        $category = $res['category'];
        
        $this->view->assign('categorydata', $categorydata);
        $this->view->assign('category', $category);
		$this->view->assign('title',date('Y'). __('年会计职称考试'));
        return $this->view->fetch('common');
		}

    public function cate_load($category_id,$cid = 0){
        $category = $categorydata = [];
        $this->model = model('app\common\model\Category');
        $this->subject = model('app\admin\model\yexam\Subject');

        $category = collection($this->model->field('id,pid,name,type,flag')->where('type', 'exam')->where('pid',$category_id)->order('weigh asc,id asc')->select())->toArray();

        $page = $this->request->get('page') ?? 1;
        $limit = $this->request->get('limit') ?? 1000;
        $subject = new \addons\yexam\service\Subject();
        $package = new \app\admin\model\Package;

        if(!$category || $cid){
			$cid = $cid ? : $category_id;
            $data = $subject->getSubjectList($page,$limit,$cid);
            if ($data['data']) {
                foreach ($data['data'] as &$item) {
                    $item['package_content'] = [];
                    if ($item['package_ids']) {
                        $package_ids = explode(',', $item['package_ids']);
                        $item['package_content'] = collection($package->where('id', 'in', $package_ids)->select())->toArray();
                    }

                    if ($item['content_json']) {
                        $item['content'] = $item['content_json'];
                    } else {
                        $item['content'] = null;
                    }
                    unset($item['content_json']);
                }
                unset($item);
                $categorydata = $data['data'];
            }
        }else{
            foreach ($category as $m=>$n){
                $data = $subject->getSubjectList($page,$limit,$n['id']);
                if ($data['data']) {
                    foreach ($data['data'] as &$item) {
                        $item['package_content'] = [];
                        if ($item['package_ids']) {
                            $package_ids = explode(',', $item['package_ids']);
                            $item['package_content'] = collection($package->where('id', 'in', $package_ids)->select())->toArray();
                        }

                        if ($item['content_json']) {
                            $item['content'] = $item['content_json'];
                        } else {
                            $item['content'] = null;
                        }
                        unset($item['content_json']);
                    }
                    unset($item);
                    $categorydata = array_merge($categorydata,$data['data']);
                }
            }
        }
        return ['category'=>$category,'categorydata'=>$categorydata];
    }

    public function cate(){
        $category_id = $this->request->param('category_id');

        $this->model = model('app\common\model\Category');
        $this->subject = model('app\admin\model\yexam\Subject');

        $tree = Tree::instance();
        $tree->init(collection($this->model->field('id,pid,name,type,flag')->where('type', 'exam')->order('weigh asc,id asc')->select())->toArray(), 'pid');
        $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $cate = $this->model->get($category_id);
        $subject_group = collection($this->subject->field('category_id, count(id) as subject_count')->group('category_id')->select())->toArray();
        $category_subject_count = array_column($subject_group, 'subject_count', 'category_id');

        $categorydata = [];

        // 最多支持三级显示
        $pre_key = null;
        $sec_key = null;
        foreach ($this->categorylist as $k => &$v) {
            $v['name'] = trim(str_replace($v['spacer'], '', $v['name']));

            if ($v['pid'] == 0) {
                $pre_key = $k;

                // 一级
                $pre_category_id = $v['id'];
                $v['subject_count'] = $category_subject_count[$v['id']] ?? 0;
                $categorydata[$pre_key] = $v;
            } else if ($v['pid'] == $pre_category_id) {
                $sec_key = $k;

                // 二级
                $v['subject_count'] = $category_subject_count[$v['id']] ?? 0;
                $categorydata[$pre_key]['childs'][$sec_key] = $v;;
            } else {
                // 三级
                $v['subject_count'] = $category_subject_count[$v['id']] ?? 0;
                $categorydata[$pre_key]['childs'][$sec_key]['childs'][] = $v;;
            }
        }
        $page = $this->request->get('page') ?? 1;
        $limit = $this->request->get('limit') ?? 100;
        $subject = new \addons\yexam\service\Subject();
        $data = $subject->getSubjectList($page,$limit,$category_id);
        $package = new \app\admin\model\Package;


        // content_json to content
        if ($data['data']) {
            foreach ($data['data'] as &$item) {
                $item['package_content'] = [];
                if ($item['package_ids']) {
                    $package_ids = explode(',', $item['package_ids']);
                    $item['package_content'] = collection($package->where('id', 'in', $package_ids)->select())->toArray();
                }

                if ($item['content_json']) {
                    $item['content'] = $item['content_json'];
                } else {
                    $item['content'] = null;
                }
                unset($item['content_json']);
            }
            unset($item);
        }
        $this->view->assign('data', $data);
        $this->view->assign('cate', $cate);
        $this->view->assign('categorydata', $categorydata);
        $this->view->assign('title', __('2021年执业医师资格考试'));
        return $this->view->fetch();
    }
}
